package com.dmz.task.controller.api;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.dmz.common.utils.secure.GMUtil;
import com.dmz.task.bean.entity.TDocInfo;
import com.dmz.task.constant.CommonCode;
import com.dmz.task.constant.GlobalConstant;
import com.dmz.task.model.ApiResult;
import com.dmz.task.service.DocInfoService;
import com.dmz.task.service.FileTaskLockService;
import com.dmz.task.service.OtherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * @author lee
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class FilePushApi {

    @Autowired
    private DocInfoService docInfoService;

    @Autowired
    private FilePush filePush;

    @Autowired
    private FileTaskLockService fileTaskLockService;

    @Autowired
    private OtherService otherService;

    @Value("${dmz.gwdl.base.dir}")
    private String gwdlDir;

    @Value("${dmz.gwdl.base.jk}")
    private String jkDir;

    @Value("${sm4.key}")
    private String key;

    @Value("${sm4.iv}")
    private String iv;

    @Value("${dmz.base.dir}")
    private String baseDir;

    @GetMapping("common/file/{fileId}")
    public ApiResult<?> pushFile(@PathVariable Long fileId) {
        TDocInfo doc = docInfoService.select(fileId);
        boolean getkey = fileTaskLockService.getkey(DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMAT) + "YJF_TASK_FILE" + fileId.toString());
        try {
            if (getkey) {
                if (doc != null && Objects.equals(doc.getDelFlag(), GlobalConstant.NOT_DELETED)) {
                    ApiResult<String> push = filePush.push(doc);
                    fileTaskLockService.releaseLock(DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMAT) + "YJF_TASK_FILE" + fileId);
                    return push;
                } else {
                    fileTaskLockService.releaseLock(DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMAT) + "YJF_TASK_FILE" + fileId);
                    return ApiResult.fail("当前任务已过期");
                }
            } else {
                //FileUtil.del(doc.getSrcPath());
                //FileUtil.mkdir(doc.getSrcPath());
                //fileTaskLockService.releaseLock(DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMAT) + "YJF_TASK_FILE" + fileId);
                return ApiResult.fail("当前任务已有进程在执行");
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            fileTaskLockService.releaseLock(DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMAT) + "YJF_TASK_FILE" + fileId);
            return ApiResult.fail(CommonCode.UNKNOWN_ERROR, e);
        }

    }

    @GetMapping("/decrypt")
    public ApiResult<String> decrypt(String text) {
        return ApiResult.success(GMUtil.db(key, iv, text));
    }

    @GetMapping("/encrypt")
    public ApiResult<String> encrypt(@RequestParam String text) {
        return ApiResult.success(GMUtil.eb(key, iv, text));
    }

    @GetMapping("/other/zynj")
    public ApiResult zynj() throws Exception {
        return otherService.zynjSftp("");
    }

    @GetMapping("/other/glfwzx")
    public ApiResult glfwzx() throws Exception {
        return otherService.fwzxdzftp();
    }

    @GetMapping("/other/mkdir")
    public ApiResult mkdir() throws IOException {
        String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        if (checkPath(gwdlDir)) {
            FileUtil.mkdir(gwdlDir + today);
        }

        if (checkPath(jkDir)) {
            FileUtil.mkdir(jkDir + today);
        }

        // 设置目录权限为777
        try {
            setPermissionsForFilesInDirectory(gwdlDir);
        } catch (IOException e) {
            // 处理异常，记录日志
            log.error(e.getMessage(), e);
        }

        try {
            setPermissionsForFilesInDirectory(gwdlDir);
        } catch (IOException e) {
            // 处理异常，记录日志
            log.error(e.getMessage(), e);
        }
        log.info("Directory permission set to 777");
        return ApiResult.success();
    }


    private void setPermissionsForFilesInDirectory(String directoryPath) throws IOException {
        File directory = new File(directoryPath);
        if (!directory.exists() || !directory.isDirectory()) {
            // 如果目录不存在或者不是目录，则不做任何操作
            return;
        }

        File[] files = directory.listFiles();
        if (files == null) {
            // 如果无法列出文件，则返回
            return;
        }

        for (File file : files) {
            // 跳过隐藏文件（以点开头的文件）
            if (file.getName().startsWith(".")) {
                continue;
            }
            // 设置文件权限为777：所有用户可读、可写、可执行
            file.setReadable(true, false);
            file.setWritable(true, false);
            file.setExecutable(true, false);
        }
    }

    private boolean checkPath(String directoryPath) throws IOException {
        boolean f = true;
        // 规范化路径
        File directory = new File(directoryPath).getCanonicalFile();
        File baseDir1 = new File(baseDir).getCanonicalFile();

        // 检查目录是否在允许的基目录下
        if (!directory.getPath().startsWith(baseDir1.getPath())) {
            f = false;
        }

        return f;
    }
}




